import { getToken } from './cookie'

/**
 * WebSocket连接类，用于处理实时消息
 */
class WebSocketService {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000 // 重连间隔，3秒
    this.messageCallbacks = new Map() // 存储不同类型消息的回调函数
    this.url = null
    this.connected = false
    this.connecting = false
    this.shouldReconnect = true // 是否应该自动重连的标志
    this.onConnectionStatusChange = null // 连接状态变更回调
  }

  /**
   * 初始化WebSocket连接
   * @param {string} url - WebSocket服务器地址
   */
  init(url) {
    if (this.connecting || this.connected) return
    
    this.url = url
    this.connecting = true
    
    const token = getToken()
    const wsUrl = `${url}?token=${token}`
    
    try {
      this.ws = new WebSocket(wsUrl)
      
      this.ws.onopen = () => {
        this.onOpen()
      }
      
      this.ws.onmessage = (event) => {
        this.onMessage(event)
      }
      
      this.ws.onerror = (error) => {
        this.onError(error)
      }
      
      this.ws.onclose = () => {
        this.onClose()
      }
    } catch (error) {
      console.error('WebSocket初始化失败:', error)
      this.connecting = false
      this.attemptReconnect()
    }
  }

  /**
   * WebSocket连接成功回调
   */
  onOpen() {
    console.log('WebSocket连接成功')
    this.connected = true
    this.connecting = false
    this.reconnectAttempts = 0
    
    // 发送心跳包
    this.startHeartbeat()
    
    // 触发连接状态变更回调
    if (typeof this.onConnectionStatusChange === 'function') {
      this.onConnectionStatusChange(true)
    }
  }

  /**
   * 收到WebSocket消息回调
   * @param {MessageEvent} event 
   */
  onMessage(event) {
    try {
      // 尝试解析JSON消息
      let data;
      try {
        data = JSON.parse(event.data);
      } catch (e) {
        // 如果不是JSON格式，直接处理原始消息
        console.log('收到非JSON消息:', event.data);
        // 如果是连接成功消息，触发连接状态变更
        if (event.data === '连接成功') {
          this.onOpen();
          return;
        }
        return;
      }

      // 检查消息类型
      if (data.type && this.messageCallbacks.has(data.type)) {
        // 直接传递整个消息对象给回调函数
        this.messageCallbacks.get(data.type)(data);
      }
      
      // 处理心跳响应
      if (data.type === 'pong') {
        // 心跳包响应，重置心跳
        this.resetHeartbeat()
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error)
    }
  }

  /**
   * WebSocket错误回调
   * @param {Event} error 
   */
  onError(error) {
    console.error('WebSocket连接出错:', error)
    this.connected = false
    
    // 触发连接状态变更回调
    if (typeof this.onConnectionStatusChange === 'function') {
      this.onConnectionStatusChange(false)
    }
  }

  /**
   * WebSocket关闭回调
   */
  onClose() {
    console.log('WebSocket连接关闭')
    this.connected = false
    this.connecting = false
    
    // 触发连接状态变更回调
    if (typeof this.onConnectionStatusChange === 'function') {
      this.onConnectionStatusChange(false)
    }
    
    // 只有在应该重连的情况下才尝试重连
    if (this.shouldReconnect) {
      this.attemptReconnect()
    }
  }

  /**
   * 尝试重新连接
   */
  attemptReconnect() {
    if (!this.shouldReconnect || this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error(`WebSocket重连停止，${this.shouldReconnect ? '已达到最大重试次数' : '已手动禁用重连'}`)
      return
    }
    
    this.reconnectAttempts++
    console.log(`WebSocket尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
    
    setTimeout(() => {
      this.init(this.url)
    }, this.reconnectInterval)
  }

  /**
   * 注册消息回调
   * @param {string} type - 消息类型
   * @param {Function} callback - 回调函数
   */
  onMessageType(type, callback) {
    this.messageCallbacks.set(type, callback)
    return this
  }

  /**
   * 发送消息
   * @param {string} type - 消息类型
   * @param {object} data - 消息数据
   */
  send(type, data) {
    if (!this.connected) {
      console.error('WebSocket未连接，无法发送消息')
      return false
    }
    
    try {
      const message = JSON.stringify({
        type,
        data
      })
      this.ws.send(message)
      return true
    } catch (error) {
      console.error('发送WebSocket消息失败:', error)
      return false
    }
  }

  /**
   * 开始心跳检测
   */
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (this.connected) {
        this.send('ping', {})
      } else {
        this.clearHeartbeat()
      }
    }, 30000) // 30秒发送一次心跳
  }

  /**
   * 重置心跳
   */
  resetHeartbeat() {
    this.clearHeartbeat()
    this.startHeartbeat()
  }

  /**
   * 清除心跳
   */
  clearHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  /**
   * 关闭连接
   */
  close() {
    // 禁用自动重连
    this.shouldReconnect = false
    this.clearHeartbeat()
    if (this.ws) {
      this.ws.close()
    }
  }

  /**
   * 启用自动重连
   */
  enableReconnect() {
    this.shouldReconnect = true
    this.reconnectAttempts = 0 // 重置重连尝试次数
  }
}

// 单例模式
export default new WebSocketService() 